<?php
namespace app\shoes\controller;
/** 控制器类引入区 **/

/** 模型类引入区 **/

use think\Db;
use app\common\model\HandCardType as HandCardTypeM;
use think\Exception;

/**
 * 手牌控制器
 * @package app\api\controller
 */
class HandCard extends Auth
{
    public $noNeedLogin = [];

    /**
     * 手牌分类列表
     */
    public function type_list()
    {
        if ($this->request->isPost()) {
            $data = HandCardTypeM::field('id,name')->select();
            $this->result('查询成功', $data, 200);
        } else {
            $this->result('请使用post请求', '', 204);
        }
    }

    /**
     * 查询手牌
     */
    public function search()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (!isset($getData['hand_card_name'])) {
                $this->result('请添加手牌', '', 204);
            }
            $find = Db::name('qt_hand_card')
                ->field('hc.id as hand_card_id,hc.name as hand_card_name,hc.status,g.id as hand_grant_id')
                ->alias('hc')
                ->leftJoin('qt_hand_grant g','hc.id = g.hand_card_id')
                ->where(['name'=>$getData['hand_card_name']])
                ->find();
            if(empty($find)){
                $this->result('未找到该手牌', '', 204);
            }
            if ($find['status'] != '2'){
                $this->result('手牌未发放', '', 204);
            }
            $this->result('查询成功', $find, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 未发放的手牌
     */
    public function no_send()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (!isset($getData['hand_card_name'])) {
                $this->result('请添加手牌', '', 204);
            }
            $find = Db::name('qt_hand_card')
                ->field('id as hand_card_id,name as hand_card_name')
                ->where(['name'=>$getData['hand_card_name'],'status'=>'1','store_id'=>$this->userInfo['store_id']])
                ->find();
            if(empty($find)){
                $this->result('手牌未发放', '', 204);
            }else{
                $this->result('查询成功', $find, 200);
            }

        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 已经发放的手牌
     */
    public function send()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (!isset($getData['hand_card_name'])) {
                $this->result('请添加手牌', '', 204);
            }
            $find = Db::name('qt_hand_card')
                ->field('hc.id as hand_card_id,hc.name as hand_card_name,hc.status,g.id as hand_grant_id')
                ->alias('hc')
                ->leftJoin('qt_hand_grant g','hc.id = g.hand_card_id')
                ->where(['hc.name'=>$getData['hand_card_name'],'hc.status'=>'2'])
                ->whereIn('g.status',['2','4'])
                ->find();
            if(empty($find)){
                $this->result('无效的手牌，或者手牌未发放', '', 204);
            }else{
                $this->result('查询成功', $find, 200);
            }
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 获取手牌配置
     */
    public function getConfig()
    {
        if ($this->request->isPost()) {
            $data = Db::name('qt_hand_card_config')
                ->where(['store_id'=>$this->userInfo['store_id'],'user_id'=>$this->userInfo['id']])
                ->find();
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 保存手牌配置
     */
    public function saveConfig()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['id'])){
                $insert = [
                    'store_id'=>$this->userInfo['store_id'],
                    'user_id'=>$this->userInfo['id'],
                    'is_auto_print'=>$getData['is_auto_print'],
                    'time'=>$getData['time'],
                ];
                $save = Db::name('qt_hand_card_config')->insert($insert);
            }else{
                $save = Db::name('qt_hand_card_config')
                    ->where(['id'=>$getData['id']])
                    ->update($getData);
            }
            if($save){
                $this->result('保存成功', '', 200);
            }
            $this->result('保存失败', '', 204);

        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 合并手牌
     */
    public function combined()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (!isset($getData['hand_grant_id']) || !isset($getData['hand_card_id']) || !isset($getData['hand_card_name'])) {
                $this->result('请选择手牌', '', 204);
            }
            //合并房间数据
            $marge = explode(',',$getData['hand_grant_id']);
            foreach ($marge as $key => $value) {
                $update = ['marge' => $getData['hand_grant_id']];
                Db::name('qt_hand_grant')->where('id', $value)->update($update);
            }
            //插入记录
            $log = [
                'hand_card_id'=>$getData['hand_card_id'],
                'hand_card_name'=>$getData['hand_card_name'],
                'hand_grant_id'=>$getData['hand_grant_id'],
                'store_id'=>$this->userInfo['store_id'],
                'user_id'=>$this->userInfo['id'],
                'create_time'=>time(),
            ];
            Db::name('qt_hand_card_marge')->insert($log);
            $this->result('合并手牌成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 删除合并手牌
     */
    public function delete_combined()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (!isset($getData['id'])) {
                $this->result('请选择合并记录ID', '', 204);
            }
            $hand_card_id = Db::name('qt_hand_card_marge')->where(['id'=>$getData['id']])->value('hand_card_id');
            $marge = explode(',',$hand_card_id);
            foreach ($marge as $key => $value) {
                $update = ['marge' => ''];
                Db::name('qt_hand_grant')->where('id', $value)->update($update);
            }
            $this->result('删除手牌成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 获取当前手牌的合并信息
     */
    public function get_marge(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (!isset($getData['hand_grant_id'])) {
                $this->result('请选择手牌', '', 204);
            }
            $handGrantId = Db::name('qt_hand_grant')->where(['id'=>$getData['hand_grant_id']])->value('marge');
            if(empty($handGrantId)){
                $handCardName[0] = Db::name('qt_hand_grant')
                    ->field('c.name,g.id as hand_grant_id,c.id as hand_card_id')
                    ->alias('g')
                    ->leftJoin('qt_hand_card c','c.id = g.hand_card_id')
                    ->where(['g.id'=>$getData['hand_grant_id']])
                    ->find();
            }else{
                $handGrantId = explode(',',$handGrantId);
                $handCardName = Db::name('qt_hand_card')
                    ->field('c.name,g.id as hand_grant_id,c.id as hand_card_id')
                    ->alias('c')
                    ->leftJoin('qt_hand_grant g','g.hand_card_id = c.id')
                    ->where(['g.status'=>'2'])
                    ->whereIn('g.id',$handGrantId)
                    ->select();
            }
            $this->result('查询成功', $handCardName, 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 转手牌
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function transfer()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if (empty($post['old_hand_card_id']) || empty($post['new_hand_card_name']) || empty($post['old_hand_grant_id'])) {
                $this->result('请选择手牌', '', 204);
            }

            $new_hand_card_data = Db::name('qt_hand_card')
                ->where('store_id', $this->userInfo['store_id'])
                ->where('name', $post['new_hand_card_name'])
                ->find();
            if (empty($new_hand_card_data)) $this->result('没有找到手牌'.$post['new_hand_card_name'] .'号','',204);

            //判断新手牌是否发放,如果手牌使用了不能发放
            $new_hand_grant_data = Db::name('qt_hand_grant')
                ->where('store_id', $this->userInfo['store_id'])
                ->where('hand_card_id', $new_hand_card_data['id'])
                ->where('status',2)
                ->find();
            if (!empty($new_hand_grant_data)) $this->result('手牌已经发放','',204);


            $project_order_data = Db::name('qt_order_project')
                ->where('hand_card_id', $post['old_hand_card_id'])
                ->where('is_delete', 2)
                ->where('is_change', 1)
                ->where('pay_status', 0)
                ->select();

            $goods_order_data = Db::name('qt_product_order_item')
                ->where(['hand_card_id' => $post['old_hand_card_id'], 'pay_status' => '0'])
                ->select();

            //检测手牌最大消费金额
            $hand_order_total_money = array_sum(array_column($project_order_data,'price')) + array_sum(array_column($goods_order_data,'goods_price'));
            $checkMoney = \app\common\model\HandCard::checkMaxMoney($new_hand_card_data['id'],$hand_order_total_money);
            if($checkMoney == false){
                $this->result('手牌超出最大消费', '', 204);
            }
            $old_grant_data = Db::name('qt_hand_grant')->where(['id' => $post['old_hand_grant_id']])->order('id desc')->find();

            //更新新房间信息
            Db::startTrans();
            try {

                //更新项目
                foreach ($project_order_data as $key => $value) {

                    Db::name('qt_order_project')
                        ->where(['id' => $value['id']])
                        ->update([
                            'hand_card_id' => $new_hand_card_data['id'],
                            'old_card_id' => $post['old_hand_card_id']
                        ]);
                }

                foreach ($goods_order_data as $key => $value) {
                    Db::name('qt_product_order_item')->where(['id' => $value['id']])
                        ->update([
                            'hand_card_id' => $new_hand_card_data['id'],
                            'old_card_id' => $post['old_hand_card_id']
                        ]);
                }

                //老手牌更改为空闲
                Db::name('qt_hand_card')->where('id', $post['old_hand_card_id'])->update(['status' => '1']);
                //老手牌记录更改为已回收
                Db::name('qt_hand_grant')->where('id', $post['old_hand_grant_id'])->update(['status' => '3']);
                //新手牌改为使用中
                Db::name('qt_hand_card')->where('id', $new_hand_card_data['id'])->update(['status' => '2']);

                //修改记录
                Db::name('qt_hand_grant')->insert([
                    'store_id' => $this->userInfo['store_id'],
                    'hand_card_id' => $new_hand_card_data['id'],
                    'grant_id' => $this->userInfo['id'],
                    'recovery_id' => '',
                    'viper_card_id' => '',
                    'money' => $old_grant_data['money'] ?? 0,
                    'payment_money' => $old_grant_data['payment_money'] ?? 0,
                    'max_money' => 0,
                    'status' => $old_grant_data['status'],
                    'create_time' => time(),
                ]);
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('转手牌失败', '', 204);
            }

            $this->result('转手牌成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 手牌转账
     */
    public function transfer_accounts()
    {
        if ($this->request->isPost()) {

            $post = $this->request->post();
            if (empty($post['old_hand_card_id']) || empty($post['new_hand_card_name']) || empty($post['old_hand_grant_id'])) {
                $this->result('请选择手牌', '', 204);
            }

            $new_hand_card_data = Db::name('qt_hand_card')
                ->where('store_id', $this->userInfo['store_id'])
                ->where('name', $post['new_hand_card_name'])
                ->find();
            if (empty($new_hand_card_data)) $this->result('没有找到手牌'.$post['new_hand_card_name'] .'号','',204);

            //判断新手牌是否发放,如果手牌使用了不能发放
            $new_hand_grant_data = Db::name('qt_hand_grant')
                ->where('store_id', $this->userInfo['store_id'])
                ->where('hand_card_id', $new_hand_card_data['id'])
                ->where('status',2)
                ->find();
            if (empty($new_hand_grant_data)) $this->result('手牌未发放','',204);


            $project_order_data = Db::name('qt_order_project')
                ->where('hand_card_id', $post['old_hand_card_id'])
                ->where('is_delete', 2)
                ->where('is_change', 1)
                ->where('pay_status', 0)
                ->select();

            $goods_order_data = Db::name('qt_product_order_item')
                ->where(['hand_card_id' => $post['old_hand_card_id'], 'pay_status' => '0'])
                ->select();

            $old_grant_money = Db::name('qt_hand_grant')->where(['id' => $post['old_hand_grant_id']])->order('id desc')->value('money');
            $new_grant_money = Db::name('qt_hand_grant')->where(['id' => $new_hand_card_data['id']])->order('id desc')->value('money');

            //更新新房间信息
            Db::startTrans();
            try {
                //更新订单房间
                //更新项目房间
                foreach ($project_order_data as $key => $value) {
                    Db::name('qt_order_project')->where(['id' => $value['id']])
                        ->update([
                            'hand_card_id' => $new_hand_card_data['id'],
                            'old_card_id'=>$post['old_hand_card_id']
                        ]);

                }
                //更新产品房间
                foreach ($goods_order_data as $key => $value) {
                    Db::name('qt_product_order_item')->where(['id' => $value['id']])
                        ->update([
                            'hand_card_id' => $new_hand_card_data['id'],
                            'old_card_id'=>$post['old_hand_card_id']
                        ]);
                }
                //新手牌增加金额
                Db::name('qt_hand_grant')->where('id', $new_hand_grant_data['id'])->update(['money' => $old_grant_money + $new_grant_money]);
                //老手牌金额为0
                Db::name('qt_hand_grant')->where('id', $post['old_hand_grant_id'])->update(['money' => 0]);

                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('转账失败', '', 204);
            }

            $this->result('转账成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }






}
